//
//  YZYPlatformLoginManager.m
//  ZCLightSDK
//
//  Created by 赵隆杰 on 2024/5/24.
//  Copyright © 2024 Vanney. All rights reserved.
//

#import "YZYPlatformLoginManager.h"
#import "YZYLoginView.h"
#import "ZCFunDataFormat.h"
#import "YZYSaccountStore.h"
#import "YZYSonUserListView.h"
#import "YZYUserInfo.h"
#import "YZYNetworkManager.h"
#import "YZYRealNameAuthenticationView.h"
#import "YZYBindPhoneView.h"
 
@interface YZYPlatformLoginManager ()
{
    BOOL isJumpAuth;//是否跳过实名认证
}

@property(nonatomic,strong) NSString *userIdentifier;

@end
 
@implementation YZYPlatformLoginManager
 
/**
 单例模式

 @return YZYPlatformLoginManager
 */
+ (instancetype)shareLoginManager {
    static YZYPlatformLoginManager *shareManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareManager = [[YZYPlatformLoginManager alloc] init];
    });
    return shareManager;
}

- (void)showLoginViewUI {
    YZYLoginView *loginView = [[YZYLoginView alloc] init];
    loginView.loginViewBlock = ^(int loginType, id  _Nonnull data, YZYLoginView * _Nonnull loginView) {
        if (loginType == 1) {
            //点击苹果登录按钮
            NSLog(@"点击苹果登录按钮");
            
        } else {
            //手机号登录返回
            NSLog(@"手机号登录返回");
            NSDictionary *resultDic = (NSDictionary *)data;
            NSString *accessToken = [ZCFunDataFormat filterString:resultDic[@"accessToken"]];
            if ([ZCFunDataFormat isBlankString:accessToken]) {
                NSLog(@"token为空，重新调用登录");
                [[YZYSaccountStore sharedInstance] makeToastFromWindow:@"token为空，重新调用登录"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showLoginViewUI];
                });
                return;
            }
            [[YZYSaccountStore sharedInstance] saveAccessToken:accessToken];

            [self requestGetUserByTokenWithUserIdentifier:@""];
        }
    };
    [loginView show];
}

/**
 拿到用户信息后判断实名认证和手机号绑定
 */
- (void)fromLoginToCheck:(YZYUserInfo *)userInfo userIdentifier:(NSString *)userIdentifier {
    NSLog(@"检查实名认证和手机号绑定");
    if (userInfo.isPhone.boolValue) {
        //已绑定手机号，判断实名认证
        NSLog(@"已绑定手机号，判断实名认证");
        if (isJumpAuth || userInfo.isAuth.boolValue) {
            NSLog(@"已认证弹出小号列表");
            YZYSonUserListView *sonUserListView = [[YZYSonUserListView alloc] initWithUserId:userInfo.userId userName:userInfo.userName];
            sonUserListView.sonUserBlock = ^(int backType, id  _Nonnull data) {
                if (self.delegate && [self.delegate respondsToSelector:@selector(phoneLoginBack:msg:userInfo:)]) {
                    if (backType == 0) {
                        //成功，更新用户信息
                        NSLog(@"小号列表点击，平台登录成功，更新用户信息");
                        NSNumber *sonId = (NSNumber *)data;
                        [[YZYNetworkManager shareManager] requestGetUserByTokenSuccess:^(NSDictionary * _Nonnull resultDict) {
                            YZYUserInfo *userInfo = [[YZYUserInfo alloc] initWithUserDict:resultDict];
                            [userInfo saveUserInfo];
                            userInfo.sonId = sonId;
                            [self.delegate phoneLoginBack:PlatformResultSuccess msg:@"平台登录成功" userInfo:userInfo];
                        } failure:^(NSString * _Nonnull error) {
                            
                        }];
                    } else if (backType == 1) {
                        //失败
                        [self.delegate phoneLoginBack:PlatformResultServerError msg:@"平台登录失败" userInfo:@""];
                    } else if (backType == 2) {
                        //切换账号
                        [self.delegate phoneLoginBack:PlatformResultChangeAccount msg:@"平台切换账号" userInfo:@""];
                    }
                }
            };
            [sonUserListView show];
        } else {
            NSLog(@"未认证去实名认证");
            YZYRealNameAuthenticationView *realNameAuthenticationView = [[YZYRealNameAuthenticationView alloc] init];
            realNameAuthenticationView.userId = userInfo.userId;
            realNameAuthenticationView.realNameAuthBlock = ^(NSNumber *isAuth) {
                if (isAuth.boolValue == NO) {
                    self->isJumpAuth = YES;
                }
                //成功实名认证,更新用户信息
                NSLog(@"成功实名认证,更新用户信息");
                [self requestGetUserByTokenWithUserIdentifier:@""];
                
            };
            [realNameAuthenticationView show];
        }
    } else {
        //弹出绑定ui让玩家输入手机号绑定
        NSLog(@"弹出绑定ui让玩家输入手机号绑定");
        YZYBindPhoneView *phoneView = [[YZYBindPhoneView alloc] init];
        phoneView.iosAuth = userIdentifier;
        phoneView.uuid = userInfo.uuid;
        phoneView.bindPhoneViewBlock = ^(int backType) {
            if (backType == 1) {
                //成功绑定,更新用户信息
                NSLog(@"成功手机号绑定,更新用户信息");
                [self requestGetUserByTokenWithUserIdentifier:userIdentifier];
            } else {
                //未绑定手机号，返回登录页
                NSLog(@"未绑定手机号，返回登录页");
                if (self.delegate && [self.delegate respondsToSelector:@selector(phoneLoginBack:msg:userInfo:)]) {
                    [self.delegate phoneLoginBack:PlatformResultChangeAccount msg:@"未绑定手机号，返回登录页" userInfo:@""];
                }
            }
        };
        [phoneView show];
    }
}

/*
 根据token获取用户信息
 */
- (void)getUserByToken {
    [self requestGetUserByTokenWithUserIdentifier:@""];
}

/*
 根据token获取用户信息
 */
- (void)requestGetUserByTokenWithUserIdentifier:(NSString *)userIdentifier {
    [[YZYNetworkManager shareManager] requestGetUserByTokenSuccess:^(NSDictionary * _Nonnull resultDict) {
        YZYUserInfo *userInfo = [[YZYUserInfo alloc] initWithUserDict:resultDict];
        [userInfo saveUserInfo];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self fromLoginToCheck:userInfo userIdentifier:userIdentifier];
        });
    } failure:^(NSString * _Nonnull error) {
        
    }];
}
 
@end
